﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace System.Windows.Controls
{
    public static class TextboxExtension
    {



        public static string GetLimitRegex(DependencyObject obj)
        {
            return (string)obj.GetValue(LimitRegexProperty);
        }

        public static void SetLimitRegex(DependencyObject obj, string value)
        {
            obj.SetValue(LimitRegexProperty, value);
        }

        public static readonly DependencyProperty LimitRegexProperty =
            DependencyProperty.RegisterAttached("LimitRegex", typeof(string), typeof(TextBox), new PropertyMetadata(null));

        /// <summary>
        /// 使用正则表达式限制文本框的输入
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="regex"></param>
        public static void LimitInput(this TextBox tb, string regex)
        {
            SetLimitRegex(tb, regex);
            tb.PreviewTextInput += Tb_PreviewTextInput;
        }

        private static void Tb_PreviewTextInput(object sender, Input.TextCompositionEventArgs e)
        {
            var regex = GetLimitRegex(sender as TextBox);
            if (!string.IsNullOrEmpty(regex))
            {
                Regex re = new Regex(regex);
                e.Handled = re.IsMatch(e.Text);
            }
        }
    }
}
